package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.android.uu.view.UURatingBar;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaImageWay;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.YjnhImageWay;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 已购买商品进行评价
 * @author GuiyouZhang
 * 2016.09.12
 */
public class CommentProductionActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_CAMERA = 0x01;
    private final static int REQUEST_ALBUM = 0x02;
    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.ratingBar)
    UURatingBar ratingBar;
    @Bind(R.id.editText)
    EditText editText;
    @Bind(R.id.tv_num)
    TextView tvNum;
    @Bind(R.id.image_grid)
    ImageGridView imageGrid;

    private YjnhImageWay imageWay;
    private Integer orderby = 0;//上传图片的排序
    private String reply_id;//评论id
    private User user;
    private int stars = 5;

    private AddImageAdapter mImageAdapter;
    private ArrayList<ImgItemsBean> mImages = new ArrayList<>();
    private ArrayList<String> compressPaths;//压缩图片的路径，用于最后删除

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_comment_production);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent it = new Intent(mContext, AlbumActivity.class);
                int size = mImages.size();
                it.putExtra("limitCount", 4 - size);// 图片选择张数限制
                it.putExtra("model", 1);// 图片是单选还是多选
                startActivityForResult(it, albumRequestCode);
            }
        };
        refreshImages();
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
    }

    @Override
    protected void setListener() {
        titleText.setText("评价");
        titleRightBtn.setText("提交");

        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                140)});
        editText.addTextChangedListener(new TextChangeListener());
        ratingBar.setStar(5);
        ratingBar.setOnRatingChangeListener(
                new UURatingBar.OnRatingChangeListener() {
                    @Override
                    public void onRatingChange(int RatingCount) {
                        stars = RatingCount;
                    }
                }
        );
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                String content = editText.getText().toString().trim();
                if (isNull(content)) {
                    XtomToastUtil.showShortToast(mContext, "请输入内容");
                    return;
                }
                String blogId = mIntent.getStringExtra("goods_id");
//                getNetWorker().goodsReplyAdd(user.getToken(), "2", blogId, content, stars + "");
                String keytype = "2";
                if (!isNull(mIntent.getStringExtra("keytype")))
                    keytype = mIntent.getStringExtra("keytype");
                getNetWorker().goodsReplyAdd(user.getToken(), keytype, blogId, content, stars + "");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compressPaths != null)
            for (String path : compressPaths) {
                File file = new File(path);
                file.delete();
            }
    }

    private void refreshImages() {
        if (mImageAdapter == null) {
            mImageAdapter = new AddImageAdapter(mContext, mImages);
            imageGrid.setAdapter(mImageAdapter);
            mImageAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (mImages.size() < 5 && position == mImages.size()) {
                        showPic();
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    mImages.remove(position);
                    mImageAdapter.notifyDataSetChanged();
                }
            });
        } else {
            mImageAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                album(data);
                break;
            case REQUEST_CAMERA:// 拍照
                camera();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void camera() {
        String imagepath = imageWay.getCameraImage();
        new CompressPicTask().execute(imagepath);
    }

    // 自定义相册选择时处理方法
    private void album(Intent data) {
        if (data == null)
            return;
        ArrayList<String> imgList = data.getStringArrayListExtra("images");
        if (imgList == null)
            return;
        for (String img : imgList) {
            new CompressPicTask().execute(img);
        }
    }

    // 调用系统相册时的处理方法
    private void albumSystem(Intent data) {
        if (data == null)
            return;
        Uri selectedImageUri = data.getData();
        // 获取图片路径
        String[] proj = {MediaStore.Images.Media.DATA};
        final CursorLoader loader = new CursorLoader(mContext);
        loader.setUri(selectedImageUri);
        loader.setProjection(proj);
        loader.registerListener(0, new OnLoadCompleteListener<Cursor>() {

            @Override
            public void onLoadComplete(Loader<Cursor> arg0, Cursor cursor) {
                int columnIndex = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                String imagepath = cursor.getString(columnIndex);
                new CompressPicTask().execute(imagepath);
                loader.stopLoading();
                cursor.close();
            }
        });
        loader.startLoading();
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case GOODS_REPLY_ADD:
                showProgressDialog("请稍候");
                break;
            case FILE_UPLOAD:
                showProgressDialog("正在上传图片");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case GOODS_REPLY_ADD:
            case FILE_UPLOAD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case GOODS_REPLY_ADD:
                HemaArrayResult<String> tResult = (HemaArrayResult<String>) baseResult;
                reply_id = tResult.getObjects().get(0);
                if (mImages.size() > 0) {
                    fileUpload();
                } else {
                    XtomToastUtil.showShortToast(mContext, "评价成功");
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1000);
                }
                break;
            case FILE_UPLOAD:
                mImages.remove(0);
                if (mImages.size() > 0) {
                    fileUpload();
                } else {
                    XtomToastUtil.showShortToast(mContext, "评价成功");
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1000);
                }
                break;
        }

    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case GOODS_REPLY_ADD:
                XtomToastUtil.showShortToast(mContext, "评论失败，"+baseResult.getMsg());
                break;
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "图片上传失败"+baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case GOODS_REPLY_ADD:
                XtomToastUtil.showShortToast(mContext, "评论失败，请稍后再试");
                break;
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "图片上传失败");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        setResult(RESULT_OK);
                        finish();
                    }
                }, 1000);
                break;
            default:
                break;
        }
    }

    private void fileUpload() {
        if (isNull(reply_id)) {
            return;
        }
        String imagePath = mImages.get(0).getImgurl();
        getNetWorker().fileUpload(user.getToken(), "16", reply_id,
                "0", orderby + "", "无", imagePath);
        orderby++;
    }

    private class TextChangeListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            tvNum.setText(s.toString().length() + "/" + 140);
        }

    }

    /**
     * 显示图片选择对话
     */
    public void showPic() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if ( mImages.size() < 4)
                                    imageWay.camera();
                                else
                                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                            }
                        })
                .addSheetItem("从相册打开", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if ( mImages.size() < 4)
                                    imageWay.album();
                                else
                                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                            }
                        })
                .show();
    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    if (compressPaths == null)
                        compressPaths = new ArrayList<>();
                    compressPaths.add(compressPath);
                    ImgItemsBean imageitem = new ImgItemsBean();
                    imageitem.setImgurl(compressPath);
                    mImages.add(imageitem);
                    refreshImages();
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }
}
